package com.ee.chat.api.interceptor;

import com.alibaba.fastjson.JSON;
import com.ee.chat.common.bean.Result;
import com.ndhutu.ee.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.MessageDigest;

/**
 * 接口验权拦截
 * @Author Shane
 * @Date 2020/5/13 17:28
 */
@Component
public class CheckSumInterceptor implements HandlerInterceptor {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource(name = "stringRedisTemplate")
    StringRedisTemplate redisTemplate;
    @Value("${encrypt.apiKey}")
    String apiKey;

    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //测试接口专用
        if("1".equals(request.getParameter("dev"))){
            return true;
        }

        Result result = null;

        String nonce = request.getHeader("nonce");
        String currTime = request.getHeader("currTime");
        String checkSum = request.getHeader("checkSum");

        log.info("nonce:"+nonce+",currTime:"+currTime+",checkSum:"+checkSum);

        if(StringUtil.isEmpty(nonce) || StringUtil.isEmpty(currTime) || StringUtil.isEmpty(checkSum)){
            result = Result.retuenIllegality();
        }

        //校验时间
        if(result == null){
            long diff = System.currentTimeMillis() - Long.parseLong(currTime);
            diff = diff < 0 ? -diff : diff;
            if(diff > 60*1000){
                log.info("时间超时");
                result = Result.retuenIllegality();
            }
        }

        //防止重复调用
        /*String key = "checkSum:"+ DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now());
        if(result == null){
            Long index = redisTemplate.opsForZSet().rank(key, checkSum);
            if(StringUtil.isEmpty(checkSum) || (index != null && index >= 0)){
                log.info("checkSum重复");
                result = Result.retuenIllegality();
            }
        }*/

        //计算checkSum
        if(result == null){
            String value = apiKey+nonce+currTime;
            MessageDigest messageDigest = MessageDigest.getInstance("sha1");
            messageDigest.update(value.getBytes());
            byte[] bytes = messageDigest.digest();

            //转换成16进制
            int len = bytes.length;
            StringBuilder buf = new StringBuilder(len * 2);
            for (int j = 0; j < len; j++) {
                buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
                buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
            }
            String newCheckSum = buf.toString();
            if(!checkSum.equals(newCheckSum)){
                log.info("checkSum错误");
                result = Result.retuenIllegality();
            }
        }

        if(result == null){
//            redisTemplate.opsForZSet().add(key, checkSum, 1);

            log.info("请求头校验通过");

            return true;
        }else{
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.append(JSON.toJSONString(result));
            pw.close();

            return false;
        }
    }

}
